<?php

namespace ai\app\web;

include_once(__DIR__ . '/user.php');
include_once(__DIR__ . '/auth.php');

use Yii;

class Web
{
    /**
     * @var User
     */
    public $user;

    /**
     * @var Auth
     */
    public $auth;

    function __construct()
    {
        $this->user = new User();
        $this->auth = new Auth();
    }

    function loadModel($app_name, $data = array())
    {
        $route = Yii::$app->controller->route;
        list($class, $action) = explode('/', $route);

        $container = new Yii\di\Container;
        $container->set('model', $app_name . "\\models\\{$class}Model");
        $model = $container->get('model');
        $data = call_user_func_array(array($model, "action{$action}"), array('a' => $data));
        $data = $data ? $data : array();
        return $data;
    }

    function verify($route, $method = 'post', $action='', $value='')
    {
        $route = strtolower($route);
        $sysID = SYS_ID;
        $roleID = ROLE_ID;

        $whereAction = '';
        if ($action && $value) {
            $whereAction = "and a.req_key='{$action}' 
and a.req_value='{$value}'";
        }

        $sql = "SELECT a.id from sys_auth_modules_actions_permissions a
INNER JOIN sys_auth_modules_actions b on a.action_id=b.id
INNER JOIN sys_auth_modules c on c.id=a.module_id
INNER JOIN sys_auth_role_permissions e on a.id=e.permissions_id
where c.sys_id={$sysID} and b.route='{$route}' {$whereAction} and (a.req_method='{$method}' or a.req_method='{$method}all') and e.role_id={$roleID}";

        $row = \Ai::$db->query->sql($sql)->one();

        if (isset($row['id']))
            return true;

        return false;
    }
}

